<?php

namespace App\Service;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

class ToolService
{
    const ERROR_QIAN = [
        '鸿运当头照，青云步步高',
        '紫气东来日，金章玉印时',
        '东风借力上瑶台，万里鹏程一掌开',
        '红鸾星动契三生，连理枝头锦绣盟',
        '比目双游情似海，画眉深浅入时无',
        '桃花灼灼宜家室，燕语莺啼岁岁春',
        '松柏长青春永驻，蟠桃盛宴宴长生',
        '杏林日暖消百恙，鹤发童颜乐有余',
        '心宽自是长生药，笑口常开福满舟',
        '金鳞出水腾云雨，宝树开花聚斗金',
        '天禄阁中传喜讯，地财库里启新篇',
        '春种玉粒秋收粟，仓满金银厩满驹',
        '蟾宫折桂非难事，雁塔题名在此签',
        '十年琢玉终成器，一日看尽长安花',
        '文曲光浮朱笔顶，墨池浪起化龙时',
        '天官赐福门楣耀，地母承恩宅第安',
        '四时顺遂无灾厄，八节康宁有吉星',
        '福如东海长流水，寿比南山不老松',
        '吉星高照千祥集，瑞气盈门万事兴',
        '心想事成皆如意，柳暗花明又一春',
    ];

    /**
     * 获取每日一签
     *
     * @return array
     */
    public function cq(): array
    {
        $url = 'https://api.t1qq.com/api/tool/cq';
        $key = config('services.ytapi.key', 'PV0C275n27a6E5R1cHksRjb6cL');
        if (empty($key)) {
            // 随机从ERROR_QIAN取一个返回
            return ['qian' => "🎐上上签", 'jie' => "🎐" . self::ERROR_QIAN[array_rand(self::ERROR_QIAN)]];
        }
        $randomNumber = mt_rand(1, 100);
        if ($randomNumber <= 3) {
            return ['qian' => "🎐上上签", 'jie' => "🎐" . self::ERROR_QIAN[array_rand(self::ERROR_QIAN)]];
        }
        try {
            $client   = new Client(['timeout' => 10]);
            $response = $client->get($url, [
                'query' => [
                    'key' => $key
                ]
            ]);
            $data     = json_decode($response->getBody()->getContents(), true);
            $qian     = $data['qian'] ?? '';
            $jie      = $data['jie'] ?? '';
            if (!$qian && !$jie) {
                return "🎐" . self::ERROR_QIAN[array_rand(self::ERROR_QIAN)] . "\n---------------\n每人每日最多一签~";
            }
            return ['qian' => "🎐$qian", 'jie' => "🎐$jie"];
        } catch (GuzzleException $e) {
            return ['qian' => "🎐上上签", 'jie' => "🎐" . self::ERROR_QIAN[array_rand(self::ERROR_QIAN)]];
        }
    }
}
